<template>
  <div v-loading="loadState">
    <el-form :inline="true">
      <el-form-item>
        <el-button
          @click="isUploading = true"
          type="primary"
          plain
          icon="el-icon-upload"
          style="margin-right: 0.1rem"
          >上传视频文件</el-button
        >
      </el-form-item>
      <el-form-item label="企业">
        <el-select
          v-model="unitId"
          multiple
          collapse-tags
          style="width: 1.5rem"
          placeholder="请选择"
          @change="selectChange"
        >
          <el-option
            v-for="item in allEnterprises"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="video-area">
      <el-row class="row" v-for="row in rows" :key="row" :gutter="gutter">
        <el-col :span="Math.floor(24 / cols)" v-for="col in cols" :key="col">
          <video-card
            v-if="toIndex(row, col) < videoList.length"
            :thumbnail-src="
              $http.defaults.baseURL +
              thumbnailUrl +
              videoList[toIndex(row, col)].id +
              (videoList[toIndex(row, col)].state === VideoStates.PROCESSING
                ? '?process'
                : '')
            "
            v-bind="videoList[toIndex(row, col)]"
            @play="play(videoList[toIndex(row, col)])"
            @more="$refs.editor.$emit('open', videoList[toIndex(row, col)])"
          ></video-card>
        </el-col>
      </el-row>
    </div>
    <el-row type="flex" justify="end">
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="currentPage"
        :total="videoList.length"
        :page-size="pageSize"
      ></el-pagination>
    </el-row>
    <el-dialog title="上传视频文件" :visible.sync="isUploading" width="50%">
      <file-upload
        :upload-method="uploadMethod"
        :on-success="loadVideos"
      ></file-upload>
    </el-dialog>
    <el-dialog
      v-if="preview.currentVideo"
      :visible.sync="preview.isPreviewing"
      width="50%"
      @close="previewClose"
    >
      <video ref="video" class="video" :src="videoSrc" controls autoplay>
        您的浏览器暂时不支持在线预览。
      </video>
    </el-dialog>
    <video-editor
      ref="editor"
      @delete-success="loadVideos"
      @change-success="loadVideos"
    ></video-editor>
  </div>
</template>

<script>
import VideoCard from "~/components/file-list/video-list/VideoCard";
import VideoStates from "~/components/file-list/video-list/VideoStates";
import FileUpload from "~/components/file-list/FileUpload";
import VideoEditor from "~/components/file-list/video-list/VideoEditor";
import {
  getDirectoryIdList,
  getUnitNameList,
} from "~/api/user";
export default {
  name: "VideoList",
  components: { VideoEditor, FileUpload, VideoCard },
  props: {
    loadRootUrl: {
      type: String,
      required: true,
    },
    rows: {
      type: Number,
      default: 2,
    },
    cols: {
      type: Number,
      default: 4,
    },
    gutter: {
      type: Number,
      default: 10,
    },
    thumbnailUrl: {
      type: String,
      default: "/group/video/thumbnail/",
    },
    listDirectoryUrl: {
      type: String,
      // default: "/group/video/ls",
      default: "/group/video/lsOverride",
    },
    uploadUrl: {
      type: String,
      default: "/group/video/upload",
    },
    previewUrl: {
      type: String,
      default: "/group/video/preview/",
    },
    defaultUnitId: {
      type: Array,
      required: false,
    },
    uniqueName: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      videoList: [],
      currentPage: 1,
      rootDir: null,
      loadState: true,
      VideoStates,
      videoSrc: "#",
      isUploading: false,
      reloadTimeout: null,
      preview: {
        isPreviewing: false,
        currentVideo: null,
      },
      //select相关数据
      allEnterprises: [],
      unitId: [],
      id: "",
    };
  },
  methods: {
    toIndex(row, col) {
      return (
        (this.currentPage - 1) * this.pageSize + (row - 1) * this.cols + col - 1
      );
    },
    responseAssert(response) {
      if (
        typeof response.data.resultCode !== "string" ||
        !response.data.resultCode.startsWith("2")
      )
        throw Error(response.message);
    },
    async loadRootMeta() {
      try {
        var unitId = this.unitId.join(",");
        const response = await this.$http.get(this.loadRootUrl, {
          params: { unitId: unitId },
        });
        this.responseAssert(response);
        return response.data.parameter;
      } catch (e) {
        console.log(e);
        let err = e;
        if (err.response && err.response.hasOwnProperty("data"))
          err = err.response.data;
        throw e;
      }
    },
    async loadList(id) {
      try {
        const response = await this.$http.get(this.listDirectoryUrl, {
          params: { idArray: id },
        });
        this.responseAssert(response);
        return response.data.parameter;
      } catch (e) {
        console.log(e);
        let err = e;
        if (err.response && err.response.hasOwnProperty("data"))
          err = err.response.data;
        throw e;
      }
    },
    async init() {
      try {
        this.rootDir = await this.loadRootMeta();
        this.id = this.rootDir.id;
      } catch (e) {
        this.$alert(e.message, "加载失败", { type: "error" });
        throw e;
      }
      this.loadVideos();
    },
    async loadVideos() {
      clearTimeout(this.reloadTimeout);
      try {
        this.videoList = (await this.loadList(this.id)).array;
        this.stateCheck();
      } catch (e) {
        this.$alert(e.message, "加载失败", { type: "error" });
        this.reloadLater();
      }
    },
    stateCheck() {
      const needFresh = this.videoList.some(
        (video) =>
          video.state === VideoStates.PROCESSING ||
          video.state === VideoStates.ENCODING
      );
      if (needFresh) this.reloadLater();
    },
    reloadLater() {
      const that = this;
      const timeout = setTimeout(() => that.loadVideos(), 10000);
      this.reloadTimeout = timeout;
      this.$on("update:beforeDestroy", () => clearTimeout(timeout));
    },
    async uploadMethod(file, uniqueId = this.id, unitId = this.unitId) {
      let formData = new FormData();
      formData.append("file", file.file);
      formData.append("parentId", uniqueId);
      formData.append("unitId", unitId);
      let source = this.$http.CancelToken.source();
      file.file.cancelSource = source;
      this.$http({
        url: this.uploadUrl,
        method: "post",
        data: formData,
        //上传进度
        onUploadProgress: (progressEvent) => {
          let num = ((progressEvent.loaded / progressEvent.total) * 100) | 0; //百分比
          file.onProgress({ percent: num }); //进度条
        },
        cancelToken: source.token,
        timeout: -1,
      })
        .then((data) => {
          file.onSuccess(data); //上传成功(打钩的小图标)
        })
        .catch((err) => {
          file.onError(err);
        });
    },
    play(v) {
      //这里会等获取到后端传过来的所有二进制流文件然后生成一个url地址(因为要带上token)，所以播放速度会相当的慢，目前还没有找到解决办法
      //想要速度加快只能后端放行或者用别的组件
      this.preview.currentVideo = v;
      this.preview.isPreviewing = true;
      this.videoSrc =
        this.$http.defaults.baseURL +
        this.previewUrl +
        this.preview.currentVideo.id;

      // let tempVideoSrc = this.$http.defaults.baseURL + this.previewUrl + this.preview.currentVideo.id
      // let token = sessionStorage.getItem('token')
      // let request = new XMLHttpRequest();
      // request.responseType = 'blob';
      // request.open('get',tempVideoSrc,true);
      // request.setRequestHeader('token',token);
      // request.onreadystatechange = e =>{
      //   if (request.readyState === XMLHttpRequest.DONE && request.status === 200){
      //     this.videoSrc = URL.createObjectURL(request.response);
      //   }
      // };
      // request.send(null);
    },
    previewClose() {
      this.$refs.video.pause();
    },
    async getUnitNameList() {
      try {
        let temp = (await getUnitNameList()).parameter;
        this.allEnterprises = temp.filter((item) => item.id !== 0);
        var unitIdArray = String(this.unitId.join(","));
        // this.id = (
        //   await getDirectoryId(this.uniqueName, { unitId:  unitId})
        // ).parameter.id;
        const res = await getDirectoryIdList(this.uniqueName, {
          unitIdArray: unitIdArray,
        });
        var idList = [];
        for (let i = 0; i < res.parameter.length; i++) {
          var id = res.parameter[i].id;
          idList.push(id);
        }
        this.id = String(idList.join(","));
      } catch (e) {
        this.$alert(e.message, "加载失败", { type: "error" });
        throw e;
      }
    },
    async selectChange() {
      var unitIdArray = String(this.unitId.join(","));
      // this.id = (
      //   await getDirectoryId(this.uniqueName, { unitId: unitId })
      // ).parameter.id;
      const res = await getDirectoryIdList(this.uniqueName, {
        unitIdArray: unitIdArray,
      });
      var idList = [];
      for (let i = 0; i < res.parameter.length; i++) {
        var id = res.parameter[i].id;
        idList.push(id);
      }
      this.id = String(idList.join(","));
      await this.loadVideos();
    },
  },
  computed: {
    pageSize() {
      return this.rows * this.cols;
    },
  },
  async mounted() {
    this.unitId = this.defaultUnitId == null ? 1 : this.defaultUnitId;
    await this.getUnitNameList();
    this.loadState = true;
    this.init().finally(() => (this.loadState = false));
    window.sessionStorage.setItem("uniqueName",this.uniqueName)
  },
};
</script>

<style scoped>
.row {
  margin-bottom: 5px;
}
.video {
  width: 100%;
}
.video-area {
  overflow: hidden;
  overflow-y: auto;
  margin-top: 0.01rem;
  height: 68vh;
}
</style>
